package com.yu.rpc.core;

import com.yu.rpc.core.config.RegistryConfig;
import com.yu.rpc.core.config.RpcConfig;
import com.yu.rpc.core.constant.RpcConstant;
import com.yu.rpc.core.registry.Registry;
import com.yu.rpc.core.registry.RegistryFactory;
import com.yu.rpc.core.utils.ConfigUtils;

public class RpcApplication {
    private static volatile RpcConfig rpcConfig;

    /**
     * 框架初始化，支持传入自定义配置
     */
    public static void init(RpcConfig newRpcConfig) {
        rpcConfig = newRpcConfig;
        System.out.println("rpc init, config = " + newRpcConfig.toString());
        // 注册中心初始化
        RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
        Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
        registry.init(registryConfig);
        System.out.println("registry init, config = " + registryConfig);
        Runtime.getRuntime().addShutdownHook(new Thread(registry::destroy));
    }

    public static void init() {
        RpcConfig newConfig;
        try {
            newConfig = ConfigUtils.loadConfig(RpcConfig.class, RpcConstant.DEFAULT_CONFIG_PREFIX);
        } catch (Exception e) {
            newConfig = new RpcConfig();
        }
        init(newConfig);
    }

    public static RpcConfig getConfig() {
        if (rpcConfig == null) {
            synchronized (RpcApplication.class) {
                if (rpcConfig == null) {
                    init();
                }
            }
        }
        return rpcConfig;
    }
}


